/*global pi, self, Image */
// 关键帧动画模块

pi.mod.define('pi.ui.ani', function(pi) {
	"use strict";
	// 定义模块
	var module = {},
	list = [],
	TIMEOUT = 40,
	// 定时执行函数
	timeout = function() {
		var ani, i, n = list.length, time = pi.lang.createDate().getTime();
		for (i = n - 1; i >= 0; i--) {
			ani = list[i];
			if (ani.isLive()) {
				ani.run(time);
			} else {
				list[i] = list[--n];
			}
		}
		if (n < list.length) {
			list.length = n;
		}
		timeout.timeRef = (n > 0) ? self.setTimeout(timeout, TIMEOUT) : undefined;
	},
	//创建动画
	create = function(url, callback, sizeReady) {
	};
	//运行动画
	start = function(url, callback, sizeReady) {
		var img = new Image();
		img.src = url;
		// 如果图片被缓存，则直接返回缓存数据
		if (img.complete) {
			callback(img);
			return;
		}
		img.sizeReady = callback;
		// 加载错误后的事件
		img.onerror = function() {
			var fun = img.sizeReady;
			delete img.sizeReady;
			img = img.onload = img.onerror = null;
			if (fun) {
				fun({
					error: "img error",
					reason: "",
					src: url
				});
			}
		};
		// 完全加载完毕的事件
		img.onload = function() {
			// onload在定时器时间差范围内可能比onready快
			var fun = img.sizeReady;
			delete img.sizeReady;
			// IE gif动画会循环执行onload，置空onload即可
			img = img.onload = img.onerror = null;
			if (fun) {
				fun(img);
			}
		};
		// 加入队列中定期执行
		if (sizeReady) {
			list.push(img);
			if (list.length === 1) {
				timeout.timeRef = self.setTimeout(timeout, TIMEOUT);
			}
		}
	};
	// 停止所有动画
	module.stop = function() {
		if (timeout.timeRef) {
			var i;
			self.clearTimeout(timeout.timeRef);
			for (i = list.length - 1; i >= 0; i--) {
				delete list[i].sizeReady;
			}
			list = [];
		}
	};
	module.start = start;
	return module;
});